// 登录页面
const form = document.querySelector('form')
const nameInp = document.querySelector('.username')
const pwdInp = document.querySelector('.password')
const errBox = document.querySelector('.err')

form.addEventListener('submit', e => {
  e = e || window.event
  try { e.preventDefault() } catch(err) { e.returnValue = false }
  const name = nameInp.value
  const pwd = pwdInp.value
  if (!name || !pwd) return alert('请完整填写表单')
  const xhr = new XMLHttpRequest()
  xhr.open('POST', 'http://localhost:8888/users/login')
  xhr.onload = function () {
    const res = JSON.parse(xhr.responseText)
    loginHandler(res)
  }
  xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
  xhr.send(`username=${ name }&password=${ pwd }`)
})

function loginHandler(res) {
  if (res.code === 0) {
    errBox.style.display = 'block'
  }
  if (res.code === 1) {
    window.localStorage.setItem('token', res.token)
    window.localStorage.setItem('id', res.user.id)
    window.location.href = './00.shouye.html'
  }
}


